package leetcode.offer_two_special.hash;

/**
 * @author mazouri
 * @create 2021-09-10 9:43
 */
public class _34_isAlienSorted {
    int[] orders;

    public boolean isAlienSorted(String[] words, String order) {
        orders = new int[order.length()];
        for (int i = 0; i < orders.length; i++) {
            orders[order.charAt(i) - 'a'] = i;
        }

        for (int i = 0; i < words.length - 1; i++) {
            if (!isSorted(words[i], words[i + 1])) return false;
        }

        return true;
    }

    private boolean isSorted(String word1, String word2) {
        int i = 0;
        while (i < word1.length() && i < word2.length()) {
            char c1 = word1.charAt(i);
            char c2 = word2.charAt(i);

            if (orders[c1 - 'a'] < orders[c2 - 'a']) return true;
            else if (orders[c1 - 'a'] > orders[c2 - 'a']) return false;

            i++;
        }
        //true说明word1和word2前面元素一样，但word2更长
        return i == word1.length();
    }
}
